package com.modules.sys.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.common.utils.R;
import com.common.utils.ShiroUtils;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.modules.sys.entity.SysUserEntity;
import com.modules.sys.service.SysUserService;
import com.modules.sys.service.SysUserTokenService;

import net.sf.json.JSONArray;

/**
 * 登录相关
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年11月10日 下午1:15:31
 */
@RestController
public class SysLoginController {
	@Autowired
	private Producer producer;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserTokenService sysUserTokenService;
	
	private String adminMenuList = "[{\"title\": \"用户列表\",\"index\": \"user\",\"childList\": [{\"text\": \"男用户列表\",\"index\": \"user.man\"}, {\"text\": \"女用户列表\",\"index\": \"user.woman\"}, {\"text\": \"女性认证列表\",\"index\": \"user.identity\"}, {\"text\": \"用户设备码列表\",\"index\": \"user.devicecode\"}]}, {\"title\": \"广播\",\"index\": \"broadCast\",\"childList\": [{\"text\": \"男士广播\",\"index\": \"broadCast.man\"}, {\"text\": \"女士广播\",\"index\": \"broadCast.woman\"}]}, {\"title\": \"邀请码\",\"index\": \"code\",\"childList\": [{\"text\": \"新用户申请\",\"index\": \"code.new\"}, {\"text\": \"老用户申请\",\"index\": \"code.old\"}]}, {\"title\": \"举报\",\"index\": \"report\",\"childList\": [{\"text\": \"男士举报\",\"index\": \"report.man\"}, {\"text\": \"女士举报\",\"index\": \"report.woman\"}]}, {\"title\": \"评价\",\"index\": \"evaluate\",\"childList\": [{\"text\": \"男士评价\",\"index\": \"evaluate.man\"}, {\"text\": \"女士评价\",\"index\": \"evaluate.woman\"}]}, {\"title\": \"提现\",\"index\": \"withdrawCash\",\"childList\": [{\"text\": \"待处理提现\",\"index\": \"withdrawCash.unhandle\"}, {\"text\": \"已处理提现\",\"index\": \"withdrawCash.handle\"}]}, {\"title\": \"系统设置\",\"index\": \"system\",\"childList\": [{\"text\": \"系统参数\",\"index\": \"system.system\"}, {\"text\": \"会员套餐\",\"index\": \"system.member\"}, {\"text\": \"系统消息\",\"index\": \"system.message\"}, {\"text\": \"收入记录\",\"index\": \"system.income\"}, {\"text\": \"客服列表\",\"index\": \"system.worker\"}]}]";
	
	private String normalMenuList = "[{\"title\": \"用户列表\",\"index\": \"user\",\"childList\": [{\"text\": \"男用户列表\",\"index\": \"user.man\"}, {\"text\": \"女用户列表\",\"index\": \"user.woman\"}, {\"text\": \"女性认证列表\",\"index\": \"user.identity\"}, {\"text\": \"用户设备码列表\",\"index\": \"user.devicecode\"}]}, {\"title\": \"广播\",\"index\": \"broadCast\",\"childList\": [{\"text\": \"男士广播\",\"index\": \"broadCast.man\"}, {\"text\": \"女士广播\",\"index\": \"broadCast.woman\"}]}, {\"title\": \"邀请码\",\"index\": \"code\",\"childList\": [{\"text\": \"新用户申请\",\"index\": \"code.new\"}, {\"text\": \"老用户申请\",\"index\": \"code.old\"}]}, {\"title\": \"举报\",\"index\": \"report\",\"childList\": [{\"text\": \"男士举报\",\"index\": \"report.man\"}, {\"text\": \"女士举报\",\"index\": \"report.woman\"}]}, {\"title\": \"评价\",\"index\": \"evaluate\",\"childList\": [{\"text\": \"男士评价\",\"index\": \"evaluate.man\"}, {\"text\": \"女士评价\",\"index\": \"evaluate.woman\"}]}, {\"title\": \"提现\",\"index\": \"withdrawCash\",\"childList\": [{\"text\": \"待处理提现\",\"index\": \"withdrawCash.unhandle\"}, {\"text\": \"已处理提现\",\"index\": \"withdrawCash.handle\"}]}]";

	@RequestMapping("captcha.jpg")
	public void captcha(HttpServletResponse response)throws ServletException, IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		//生成文字验证码
		String text = producer.createText();
		//生成图片验证码
		BufferedImage image = producer.createImage(text);
		//保存到shiro session
		ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		IOUtils.closeQuietly(out);
	}

	/**
	 * 登录
	 */
	@RequestMapping(value = "/sys/login", method = RequestMethod.POST)
	public Map<String, Object> login(SysUserEntity sysUserEntity)throws IOException {
//		String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
//		if(!captcha.equalsIgnoreCase(kaptcha)){
			// return R.error("验证码不正确");
//		}
		try {
			//用户信息
			SysUserEntity user = sysUserService.queryByUserName(sysUserEntity.getUsername());

			//账号不存在、密码错误
			if(user == null || !user.getPassword().equals(new Sha256Hash(sysUserEntity.getPassword(), user.getSalt()).toHex())) {
				return R.error("账号或密码不正确");
			}

			//账号锁定
			if(user.getStatus() == 0){
				return R.error("账号已被锁定,请联系管理员");
			}

			//生成token，并保存到数据库
			R r = sysUserTokenService.createToken(user.getUserId());
			
			// 最高权限
			if(user.getUserId() == 1L) {
				r.put("userId", user.getUserId());
				r.put("authority", JSONArray.fromObject(adminMenuList));
			}else{
				r.put("authority", JSONArray.fromObject(normalMenuList));				
			}
			
			r.put("userName", user.getUsername());
			r.put("isAdmin", user.getUserId() == 1L?1 : 0);	//是否最高权限
			
			return R.success().put("data", r);
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return R.error();
	}
	
}
